package battleship.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

@SuppressWarnings("serial")
public class SetupFieldGui extends JPanel{
	
	int x = 10;  //default sizes
	int y = 10;
	
	private SpinnerNumberModel heightModel;
	private SpinnerNumberModel widthModel;
	
	private JSpinner height;
	private JSpinner width;
	
	private JLabel heightText;
	private JLabel widthText;
	
	private JScrollPane scrollable;
	private ResizingField fieldPreview;
	
	private JPanel	spinnerGroup;
	
	public SetupFieldGui()
	{
		makeComponents();
		addLayout();
		addListeners();
	}

	
	public void makeComponents()
	{
		heightModel = new SpinnerNumberModel(10, 10, 26, 1);
		height = new JSpinner(heightModel);
		heightText = new JLabel("height:");
		
		widthModel = new SpinnerNumberModel(10,10,26,1);
		width = new JSpinner(widthModel);
		widthText = new JLabel("width:");
		
		fieldPreview = new ResizingField();
		fieldPreview.setPreferredSize(new Dimension(x * 25 + 10, y * 25 + 10));
		scrollable = new JScrollPane(fieldPreview);
		scrollable.setPreferredSize(new Dimension(300,300));
		
		spinnerGroup = new JPanel(new FlowLayout());
		
		
	}
	
	public int getXField()
	{
		return x;
	}
	
	public int getYField()
	{
		return y;
	}
	
	public JPanel getSpinnerGroup()
	{
		return spinnerGroup;
	}
	
	public void addLayout()
	{
		spinnerGroup.add(heightText);
		spinnerGroup.add(height);
		spinnerGroup.add(widthText);
		spinnerGroup.add(width);
		
		setLayout(new BorderLayout());
		
		add(spinnerGroup, BorderLayout.SOUTH);
		add(scrollable, BorderLayout.CENTER);
		
	}
	
	public void addListeners()
	{
		height.addChangeListener(new ValueChangeListener());
		width.addChangeListener(new ValueChangeListener());
	}
	
	class ValueChangeListener implements ChangeListener
	{

		@Override
		public void stateChanged(ChangeEvent e) {
			JSpinner source = (JSpinner) e.getSource();
			
			if (source.equals(height))
			{
				y = ((Number) height.getValue()).intValue();
				
				fieldPreview.paintGrid(y, x);
				fieldPreview.setPreferredSize(new Dimension(x * 25 + 10, y * 25 + 10));
			
				scrollable.revalidate();
			}
			else 
			{
				x = ((Number) width.getValue()).intValue();
			
				fieldPreview.paintGrid(y, x);
				fieldPreview.setPreferredSize(new Dimension(x * 25 + 10, y * 25 + 10));
				
				scrollable.revalidate();
			}
			
			repaint();
		}
		
	}
}
